/*	This file is part of LSAC.

	LSAC is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	LSAC is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with LSAC.  If not, see <http://www.gnu.org/licenses/>.

	Copyright (c) 2010 LEPESME "Jiboo" Jean-Baptiste
*/

#include "cASTree.h"
#include "lsac.h"
#include "cMain.h"

#include <typeinfo>

cASTree::~cASTree()
{
	list<cBlock*>::iterator lIterator = this->dBlocks.begin();
	for(; lIterator != this->dBlocks.end(); lIterator++)
	{
		delete (*lIterator);
	}
}

void cASTree::print()
{
	int pLevel = 0;
	PRINT_LOG("cASTree " << this);
	PRINT_LOG("{");
	list<cBlock*>::iterator lIterator = this->dBlocks.begin();
	for(; lIterator != this->dBlocks.end(); lIterator++)
	{
		(*lIterator)->print(pLevel + 1);
	}
	PRINT_LOG("}");
}

void cASTree::validate()
{
	cSemContext *lContext = new cSemContext();
	bool lMain = false;
	list<cBlock*>::iterator lIterator = this->dBlocks.begin();
	for(; lIterator != this->dBlocks.end(); lIterator++)
	{
		(*lIterator)->validate(lContext);
		if(typeid(*(*lIterator)) == typeid(cMain))
		{
			if(lMain) ERROR("Erreur en " << (*lIterator)->dLocation << " un programme principal a déja etait defini.");
			lMain = true;
		}
	}
	if(!lMain) ERROR("Le programme ne contient pas de programme principal.");
	delete lContext;
}

void cASTree::genCode(ostream &pStream)
{
	pStream << "#include <cstdlib>" << endl;
	pStream << "#include <iostream>" << endl;
	list<cBlock*>::iterator lIterator = this->dBlocks.begin();
	for(; lIterator != this->dBlocks.end(); lIterator++)
	{
		(*lIterator)->genCode(pStream);
	}
}
